package br.perfiman.dao.impl;

import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import br.perfiman.dao.TradeDAOService;
import br.perfiman.model.Asset;
import br.perfiman.model.Trade;

/**
 *
 * @author Wagner Costa
 * @since 27/12/2007
 * @version 1.0
 *
 */
@Stateless
public class TradeDAOServiceBean extends AbstractDAOServiceBean<Trade> implements TradeDAOService {

	@PersistenceContext(unitName="perfiman")
    public EntityManager em;

	@Override
	public EntityManager getEntityManager() {
		return em;
	}

	@SuppressWarnings("unchecked")
	public List<Trade> getTradesByDate(Asset asset, Date date) {
		return em.createQuery("FROM Trade t where t.asset.id like :assetId AND t.date = :date")
			.setParameter("assetId", asset.getId())
			.setParameter("date", date)
			.getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Trade> findByExample(Trade trade) {
		return em.createQuery("FROM Trade t where t.operationType = :operationType")
		.setParameter("operationType", trade.getOperationType())
		.getResultList();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Trade> retrieveAll() throws Exception {
		return em.createQuery("FROM Trade order by date").getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Trade> retrieveTradesByPeriod(Date initialDate, Date finalDate, Integer type) {
		return em.createQuery("FROM Trade t " +
				"				where t.date between :initialDate AND :finalDate " +
				"					AND t.type = :type")
		.setParameter("initialDate", initialDate)
		.setParameter("finalDate", finalDate)
		.setParameter("type", type)
		.getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Trade> getNewTrades(Trade trade) {
		return em.createQuery("FROM Trade t " +
				"				where t.date > :date " +
				"					AND t.asset.id = :assetId " +
				"					Order by t.date")
		.setParameter("date", trade.getDate())
		.setParameter("assetId", trade.getAsset().getId())
		.getResultList();
	}
}
